package by.semerikov.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import by.semerikov.constants.ProposalStates;
import by.semerikov.constants.Results;
import by.semerikov.constants.Roles;
import by.semerikov.exceptions.ConnectorException;
import by.semerikov.exceptions.DAOException;
import by.semerikov.form.SaveProposalVsDriverForm;
import by.semerikov.model.Person;
import by.semerikov.model.Proposal;
import by.semerikov.service.PersonService;
import by.semerikov.service.ProposalService;
import by.semerikov.service.ServiceFactory;

public class SaveProposalVSDriver extends SecuredAction {

	@Override
	public ActionForward executedInternal(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response, Person user) throws DAOException,
			ConnectorException {
		SaveProposalVsDriverForm _form = (SaveProposalVsDriverForm) form;
		Proposal newProposal = new Proposal(_form.getTripId(), null, null,
				null, null, null, ProposalStates.FREE, null);
		Person newPerson = new Person(_form.getDriverId(), null, null,
				Roles.DRIVER, null, null);
		ProposalService proposalService = ServiceFactory.getInstance()
				.getProposalService();
		PersonService personService = ServiceFactory.getInstance()
				.getPersonService();
		List<Proposal> resultTrips = proposalService.getProposal(newProposal);
		List<Person> resultDrivers = personService.getPersonsEqual(newPerson);
		if (resultTrips != null && resultTrips.size() > 0
				&& resultDrivers != null && resultDrivers.size() > 0) {
			Proposal updatedProposal = resultTrips.get(0);
			updatedProposal.setState(ProposalStates.WAIT);
			updatedProposal.setDriver(resultDrivers.get(0));
			proposalService.updateProposal(updatedProposal);
		}
		return mapping.findForward(Results.SUCCESS);
	}
}
